<template>
  <div class="course-video">
    <el-card>
      <el-form>
        <el-form-item label="视频上传">
          <input type="file" ref="video-file">
        </el-form-item>
        <el-form-item label="封面上传">
          <input type="file" ref="image-file">
        </el-form-item>
        <el-button
          type="primary"
          @click="handleUpload"
        >开始上传</el-button>
        <el-button>返回</el-button>
        <el-form-item>
          <p v-if="uploadPercent!==0">视频上传中:{{ uploadPercent }}%</p>
          <p v-if="isUploadSuccess">视频转码中: {{ isTranscodeSuccess ? '完成' : '视频转码中...'}}</p>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  aliyunImagUploadAddressAndAuth,
  aliyunVideoUploadAddressAndAuth,
  aliyunTransCode,
  aliyunTransCodePercent
} from '@/services/aliyun'
export default {
  data () {
    return {
      imageUrl: '',
      uploader: null,
      videoId: '',
      uploadPercent: 0,
      isUploadSuccess: false,
      isTranscodeSuccess: false
    }
  },
  props: {
    courseId: {
      type: [Number, String],
      required: true
    }
  },
  created () {
    this.initUploader()
  },
  methods: {
    initUploader () {
      this.uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值
        userId: '1618139964448548',
        // 上传到视频点播的地域，默认值为'cn-shanghai'，// eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async (uploadInfo) => {
          // 1.声明变量储存得到上传凭证
          let uploadAddressAndAuth = null
          // 2.根据 isImage 检测上传文件类型
          if (uploadInfo.isImage) {
            // 图片处理
            const { data } = await aliyunImagUploadAddressAndAuth()
            if (data.code === '000000') {
              // 3.data.data 即为凭证信息组成的对象
              uploadAddressAndAuth = data.data
              // 5.保存图片地址，给视频接口使用
              this.imageUrl = uploadAddressAndAuth.imageURL
            }
          } else {
            // 视频处理
            // 4. 视频接口需要上传图片封面地址，因此需要先发图再发视频
            const { data } = await aliyunVideoUploadAddressAndAuth({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageUrl
            })
            if (data.code === '000000') {
              // 6. 储存凭证
              uploadAddressAndAuth = data.data
              // 储存videoId
              this.videoId = data.data.videoId
            }
          }
          // 二、设置凭证
          this.uploader.setUploadAuthAndAddress(
            uploadInfo,
            uploadAddressAndAuth.uploadAuth,
            uploadAddressAndAuth.uploadAddress,
            uploadAddressAndAuth.imageId || uploadAddressAndAuth.videoId
          )
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
          // 只对视频上传进行监视
          if (!uploadInfo.isImage) {
            this.uploadPercent = Math.floor(loadedPercent * 100)
          }
        },
        // 上传凭证或STS token超时
        onUploadTokenExpired: function (uploadInfo) {
        },
        // 全部文件上传结束
        onUploadEnd: async (uploadInfo) => {
          this.isUploadSuccess = true
          // 视频上传成功，进行转码处理
          const { data } = await aliyunTransCode({
            lessonId: this.$route.query.lessonId,
            coverImageUrl: this.imageUrl,
            fileName: this.$refs['video-file'].files[0].name,
            fileId: this.videoId
          })
          if (data.code === '000000') {
            // 转码成功后，需要轮询转码进度
            const timer = setInterval(async () => {
              const { data } = await aliyunTransCodePercent(this.$route.query.lessonId)
              // console.log(data)
              if (data.data === 100) {
                this.isTranscodeSuccess = true
                // 当进度为 100 时，清除定时器，并提示转码成功
                clearInterval(timer)
                this.$message.success('转码成功！')
              }
            }, 1000)
          }
        }
      })
    },
    handleUpload () {
      // 获取上传的视频和图片
      const videoFile = this.$refs['video-file'].files[0]
      const imageFile = this.$refs['image-file'].files[0]
      const uploader = this.uploader
      // 添加上传文件至上传列表中
      uploader.addFile(imageFile)
      uploader.addFile(videoFile)
      // 开始上传
      //  - 开始上传后，上面文件会按添加顺序依次上传
      //  - 这时会触发 onUploadStrated 事件
      uploader.startUpload()
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
